class SettingsManager {
  constructor() {
    this.defaultSettings = {
      // 用户设置
      deviceName: '',
      autoConnect: true,

      // 消息设置
      messageNotifications: true,
      messageSound: true,
      enterToSend: true,
      showTimestamps: true,
      messageHistoryLimit: 100,

      // 文件传输设置
      fileNotifications: true,
      autoDownload: false,
      downloadPath: '',
      maxFileSize: 100, // GB

      // 通话设置
      callNotifications: true,
      callSound: true,
      videoQuality: 'hd', // 'sd', 'hd', 'fhd'
      audioInput: 'default',
      audioOutput: 'default',
      videoInput: 'default',
      echoCancellation: true,
      noiseSuppression: true,
      autoGainControl: true,

      // 界面设置
      theme: 'light', // 'light', 'dark'
      language: 'zh-CN', // 'zh-CN', 'en-US'
      fontSize: 'medium', // 'small', 'medium', 'large'
      compactMode: false,

      // 隐私设置
      readReceipts: true,
      typingIndicators: true,
      lastSeenStatus: true,

      // 高级设置
      reconnectAttempts: 10,
      heartbeatInterval: 30000, // ms
      discoveryTimeout: 10000, // ms
      callTimeout: 60000, // ms
    };

    this.settings = this.loadSettings();
    this.eventHandlers = {};
  }

  loadSettings() {
    try {
      const stored = localStorage.getItem('lanchat-settings');
      if (stored) {
        return { ...this.defaultSettings, ...JSON.parse(stored) };
      }
    } catch (error) {
      console.error('Error loading settings:', error);
    }
    return { ...this.defaultSettings };
  }

  saveSettings() {
    try {
      localStorage.setItem('lanchat-settings', JSON.stringify(this.settings));
      this.emit('settings-changed', this.settings);
      return true;
    } catch (error) {
      console.error('Error saving settings:', error);
      return false;
    }
  }

  get(key) {
    return this.settings[key];
  }

  set(key, value) {
    this.settings[key] = value;
    return this.saveSettings();
  }

  update(updates) {
    this.settings = { ...this.settings, ...updates };
    return this.saveSettings();
  }

  reset() {
    this.settings = { ...this.defaultSettings };
    return this.saveSettings();
  }

  getAll() {
    return { ...this.settings };
  }

  on(event, handler) {
    if (!this.eventHandlers[event]) {
      this.eventHandlers[event] = [];
    }
    this.eventHandlers[event].push(handler);
  }

  off(event, handler) {
    if (!this.eventHandlers[event]) {
      return;
    }
    if (handler) {
      this.eventHandlers[event] = this.eventHandlers[event].filter(h => h !== handler);
    } else {
      this.eventHandlers[event] = [];
    }
  }

  emit(event, data) {
    if (this.eventHandlers[event]) {
      this.eventHandlers[event].forEach(handler => handler(data));
    }
  }

  // 获取可用的媒体设备
  async getMediaDevices() {
    try {
      const devices = await navigator.mediaDevices.enumerateDevices();
      return {
        audioInputs: devices.filter(d => d.kind === 'audioinput'),
        audioOutputs: devices.filter(d => d.kind === 'audiooutput'),
        videoInputs: devices.filter(d => d.kind === 'videoinput')
      };
    } catch (error) {
      console.error('Error getting media devices:', error);
      return {
        audioInputs: [],
        audioOutputs: [],
        videoInputs: []
      };
    }
  }

  // 导出设置
  exportSettings() {
    const dataStr = JSON.stringify(this.settings, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `lanchat-settings-${Date.now()}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  }

  // 导入设置
  async importSettings(file) {
    try {
      const text = await file.text();
      const imported = JSON.parse(text);
      this.settings = { ...this.defaultSettings, ...imported };
      this.saveSettings();
      return true;
    } catch (error) {
      console.error('Error importing settings:', error);
      return false;
    }
  }
}

export default SettingsManager;
